import { Component, OnInit, OnDestroy } from '@angular/core';
import { Platform, NavController } from '@ionic/angular';
import { DomSanitizer } from '@angular/platform-browser';
import { ConfigService } from 'src/app/service/config.service';
import { UrlService } from 'src/app/service/url.service';
import { ActivatedRoute, Params } from '@angular/router';
import * as $ from 'jquery';
import { ToolService } from 'src/app/service/tool.service';
import { HttpService } from 'src/app/service/http.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { Clipboard } from '@ionic-native/clipboard/ngx';

@Component({
  selector: 'app-accountrechargeweb',
  templateUrl: './accountrechargeweb.page.html',
  styleUrls: ['./accountrechargeweb.page.scss'],
})
export class AccountrechargewebPage implements OnInit,OnDestroy {
  public url:any;
  private money:Number;
  private channel_way_id:String;
  private origin:String;
  private account_name:String;
  private account_no:String;
  public cardMsg={"amount":"","bankflag":"","cardnumber":"","cardname":"","location":"","note":"","order_no":"","timeout":"","notice":"","first_pre":"","first_post":"","account_bankname":"","account_name":""};
  public errorMsg="";
  public isShow=false;

  private timerArr=[];  //时间到计时的数组

  constructor(private plt:Platform,private domSanitizer:DomSanitizer,private activeRoute:ActivatedRoute,private navCtrl:NavController,private http:HttpService,private popWin:PopwinService,private clipboard:Clipboard) {
      this.activeRoute.queryParams.subscribe((params:Params)=>{
        let tempDeal=JSON.parse(ToolService.paramAESDecrypt(params['p']));
          this.money=parseInt(tempDeal['num']);
          this.channel_way_id=tempDeal['wid'];
          this.origin=tempDeal['code'];
          this.account_name=tempDeal['account_name'];
          this.account_no=tempDeal['account_no'];
      });
  }

  ngOnInit() {
    if (this.plt.is("ios")) {
     // this.url = this.domSanitizer.bypassSecurityTrustResourceUrl(ConfigService.SERVER_PATH + "" + UrlService.OTHER_NETPAY + "?token=" + $("app-root").attr("token") + "&sessid=" + $("app-root").attr("sessid")+"&money="+this.money+"&channel_way_id="+this.channel_way_id);
    } else {
     // this.url = this.domSanitizer.bypassSecurityTrustResourceUrl(ConfigService.SERVER_PATH + "" + UrlService.OTHER_NETPAY + "?token=" + $("app-root").attr("token")+"&money="+this.money+"&channel_way_id="+this.channel_way_id);
    }
    this.clearT();
    this.payNet(this.money,this.channel_way_id,this.origin,this.account_name,this.account_no);
  }

  payNet(money, channel_way_id, origin,account_name,account_no) {
    let that = this;
    let obj = "{\"money\":\"" + money + "\",\"channel_way_id\":\"" + channel_way_id + "\",\"origin\":\"" + origin + "\",\"version\":\"2\",\"account_name\":\"" + account_name + "\"}";
    if(!ToolService.isEmpty(account_no)){
      obj = "{\"money\":\"" + money + "\",\"channel_way_id\":\"" + channel_way_id + "\",\"origin\":\"" + origin + "\",\"version\":\"2\",\"account_name\":\"" + account_name + "\",\"account_no\":\"" + account_no + "\"}";    
    }
    console.log("参数的值:",obj);
    this.http.get(UrlService.OTHER_INCASH2, { "callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj) }).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        //成功的逻辑
        let resData = ToolService.aesDecodeToJson(data.data);
        console.log("支付成功的数据================:",resData);
        if(ToolService.isEmpty(resData.data) || resData.data.length<=0){
          that.isShow=false;
          that.cardMsg={"amount":"","bankflag":"","cardnumber":"","cardname":"","location":"","note":"","order_no":"","timeout":"","notice":"","first_pre":"","first_post":"","account_bankname":"","account_name":""};
          that.errorMsg=resData.message;
          that.clearT();
        }else{
          that.isShow=true;
          that.cardMsg={"amount":resData.data.amount,"bankflag":resData.data.card.bankflag,"cardnumber":resData.data.card.cardnumber,"cardname":resData.data.card.cardname,"location":resData.data.card.location,
          "note":resData.data.note,"order_no":resData.data.order_no,"timeout":resData.data.timeout,"notice":resData.data.notice,"first_pre":resData.data.first_pre,"first_post":resData.data.first_post,"account_bankname":resData.data.account_bankname,"account_name":resData.data.account_name}
          let timerOut=setTimeout(function(){
            that.countFun();
            clearTimeout(timerOut);
          },10);
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  backClick(){
    this.navCtrl.navigateBack("/accountrecharge")
  }

  timer(val){
    return ToolService.formateTime(val, true);
  }

  countFun(){
    let targetObj=$(".timer-out .t");
    let tempTimer=parseInt(targetObj.attr("data-time"));
    let tempTimerInterval= setInterval(function(){
      tempTimer--;
      if(tempTimer<=0){
        targetObj.html("订单已关闭");
      }else{
        targetObj.attr("data-time",tempTimer);
        targetObj.html(ToolService.formateTime(tempTimer, true));
      }
    },1000);
    this.timerArr.push(tempTimerInterval);
  }

  clearT(){
     this.clearTimerFun(this.timerArr,false);
     this.timerArr.length=0;
  }

  clearTimerFun(timer,isTimeOut?:boolean) {
    if (timer.length > 0) {
      for (let i = 0; i < timer.length; i++) {
        if(isTimeOut){
          clearTimeout(timer[i]);
        }else{
          clearInterval(timer[i]);
        }
        timer[i]=null;
      }
    }
  }

  copyFun(text: any) {
    if (this.plt.is("cordova")) {
      this.clipboard.copy(text).then(() => {
        this.popWin.toast("已复制到剪切板");
      });
    } else {
      let save = function (e) {
        e.clipboardData.setData('text/plain', text);   //保存到剪切板
        e.preventDefault(); //阻止默认行为
      }
      document.addEventListener('copy', save);
      document.execCommand("copy");     //使文档处于可编辑状态，否则无效
      this.popWin.toast("已复制到剪切板");
    }
  }

  copyText(text: any) {
    this.copyFun(text);
  }

  ngOnDestroy(){
    this.clearT();
  }



}
